<template>

    <el-dialog
            :title=title
            :visible.sync="dialogVisible"
            :show-close="false"
            @open="open"
            width="30%">
        <el-tree
                ref="tree"
                :data="data"
                show-checkbox
                default-expand-all
                node-key="code"
                :props="defaultProps">
        </el-tree>

        <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitPrivilege()">确 定</el-button>
            <el-button @click="cancel()">取 消</el-button>
        </span>
    </el-dialog>

</template>

<script>
    import {systemApi,commonApi} from "../../api/api";

    export default {
        data() {
            return {
                data: [],
                defaultProps: {
                    children: 'children',
                    label: 'label'
                },
                dialogVisible: false,
                row: null,
            };
        },
        computed: {
            title() {
                return this.row ? this.row.name + "分配权限" : "分配权限"
            }
        },
        created() {
            systemApi.menuTree().then(res => {
                this.data = res.data.data;
            })
        },
        methods: {
            setData(key, value) {
                this[key] = value
                return this
            },
            cancel() {
                this.dialogVisible = false
            },
            submitPrivilege() {
                let nodes = this.$refs['tree'].getCheckedKeys()
                let halfCheckedNodes = this.$refs['tree'].getHalfCheckedKeys();
                let data = {
                    roleId: this.row.id,
                    codes: [...nodes, ...halfCheckedNodes]
                }
                systemApi.addPrivilege(data).then(commonApi.popoverSuccessMessage, commonApi.popoverErrorMessage).catch(commonApi.popoverErrorMessage);
                this.dialogVisible = false;
            },
            open() {
                systemApi.rolePrivilegeCodes({roleId: this.row.id}).then(res => {
                    let resData = res.data.data;
                    this.$refs['tree'].setCheckedKeys([])
                    resData.forEach((code) => {
                        this.$nextTick(() => {
                            let node = this.$refs['tree'].getNode(code);
                            if (node.isLeaf) {//判断是否是子节点
                                this.$refs['tree'].setChecked(node, true);
                            }
                        })

                    });

                }, commonApi.popoverErrorMessage).catch(commonApi.popoverErrorMessage)
            }
        }
    };
</script>


<style>

</style>